package www.sharetime.weshare.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Json 解析工具类，借助Gson
 */
public class JsonUtils {

    private static GsonBuilder gsonb = null;

    static {
        gsonb = new GsonBuilder();
    }

    /**
     * 这块儿很可能抛异常，在具体调用处处理吧
     * <p/>
     * 将一个json 字符串解析为 bean 对象
     *
     * @param jsonString
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T toBean(String jsonString, Type type) {
        // Gson gson = gsonb.create();
        final String dateformat = "yyyy-MM-dd HH:mm:ss";
        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
            public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                SimpleDateFormat format = new SimpleDateFormat(dateformat, Locale.getDefault());
                return new JsonPrimitive(format.format(src));
            }
        }).setDateFormat(dateformat).create();
        L.et("gson", "--JsonUtils.toBean--jsonString:" + jsonString);
        if (jsonString != null && !jsonString.equals("{}") && !jsonString.equals("[]")) {
            return gson.fromJson(jsonString, type);
        } else {
            return null;
        }
    }

    /**
     * 这块儿很可能抛异常，在具体调用处处理吧
     *
     * 将对象转为json字符串
     * @param bean
     * @return
     * @throws Exception
     */
    public static String toString(Object bean) throws Exception {
        Gson gson = gsonb.create();
        return gson.toJson(bean);
    }


    public static<T> T jsonToBean(String jsonResult,Class<T> clz){
        Gson gson = new Gson();
        T t = gson.fromJson(jsonResult, clz);
        return t;
    }




}
